/*
 * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
 * Copyright (C) 2007 Alp Toker <alp@atoker.com>
 * Copyright (C) 2008 Jon Hohle <jonhohle@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "util.h"
#include <assert.h>


char* createStringWithContentsOfFilePointer(FILE* f)
{
    size_t buffer_size = 0;
    size_t buffer_capacity = 1024;
    char* buffer = (char*) malloc(buffer_capacity);
    
    while (!feof(f) && !ferror(f))    
    {
        buffer_size += fread(buffer + buffer_size, 1, buffer_capacity - buffer_size, f);
        if (buffer_size == buffer_capacity) // guarantees space for trailing '\0'
        {
            buffer_capacity *= 2;
            buffer = (char*) realloc(buffer, buffer_capacity);
            assert(buffer);
        }
        assert(buffer_size < buffer_capacity);
    }
    
    buffer[buffer_size] = '\0';
    
    return buffer;
}

char* createStringWithContentsOfFile(const char* fileName)
{
    FILE* f = fopen(fileName, "r");
    if (!f)
    {
        fprintf(stderr, "Could not open file: %s\n", fileName);
        return 0;
    }
    
    char* contents = createStringWithContentsOfFilePointer(f);
    
    fclose(f);
    
    return contents;
}



char* UTF8CStringFromJSValueRef(JSContextRef context, JSValueRef stringRef)
{
    JSStringRef string = JSValueToStringCopy(context, stringRef, NULL);
    size_t sizeUTF8 = JSStringGetMaximumUTF8CStringSize(string);
    char* stringUTF8 = malloc(sizeUTF8);
    JSStringGetUTF8CString(string, stringUTF8, sizeUTF8);
    JSStringRelease(string);
    return stringUTF8;
}


JSValueRef JSValueRefFromUTF8CString(JSContextRef context, char* string)
{
    JSStringRef stringRef = JSStringCreateWithUTF8CString(string);
    JSValueRef valueRef = JSValueMakeString(context, stringRef);
    JSStringRelease(stringRef);
    return valueRef;
}

JSValueRef JSValueRefMakeNewHash(JSContextRef context, size_t fieldCount, JSEHashEntry fields[])
{
    JSObjectRef globalObject = JSContextGetGlobalObject(context);
    
    JSStringRef hashString = JSStringCreateWithUTF8CString("Object");
    JSValueRef hashRef = JSObjectGetProperty(context,
                                              globalObject,
                                              hashString,
                                              NULL);
    JSObjectRef hashConstructor = JSValueToObject(context,
                                                   hashRef,
                                                   NULL);
    JSStringRelease(hashString);
    JSValueRef hash = JSObjectCallAsConstructor(context, 
                                                 hashConstructor, 
                                                 0, 
                                                 NULL, 
                                                 NULL);
    JSObjectRef hashObject = JSValueToObject(context,
                                              hash,
                                              NULL);
    
    unsigned int i = 0;
    for (i = 0; i < fieldCount; ++i)
    {
        JSStringRef property = JSStringCreateWithUTF8CString(fields[i].property);
        JSObjectSetProperty(context,
                            hashObject,
                            property,
                            fields[i].value,
                            kJSPropertyAttributeNone,
                            NULL);
        JSStringRelease(property);
    }
    
    
    
    return hash;
}

JSValueRef JSValueMakeErrnoError(JSContextRef context, errno_t errorNumber)
{
    JSValueRef exception;
    char* strError = strerror(errorNumber);
    JSStringRef stringError = JSStringCreateWithUTF8CString(strError);
    JSValueRef errorRef = JSValueMakeString(context, stringError);
    free(strError);
    JSStringRelease(stringError);
    
    JSStringRef stringErrorName = JSStringCreateWithUTF8CString("SystemError");
    JSValueRef errorNameRef = JSValueMakeString(context, stringErrorName);
    JSStringRelease(stringErrorName);
    
    JSEHashEntry fields[] = {
        {"name", errorNameRef},
        {"message", errorRef},
        {"errno", JSValueMakeNumber(context, errorNumber)}
    };
    
    exception = JSValueRefMakeNewHash(context, 3, fields);
    return exception;
}

JSValueRef JSValueMakeDate(JSContextRef context, struct timespec time)
{
    JSObjectRef globalObject = JSContextGetGlobalObject(context);
    
    JSStringRef dateString = JSStringCreateWithUTF8CString("Date");
    JSValueRef dateRef = JSObjectGetProperty(context,
                                             globalObject,
                                             dateString,
                                             NULL);
    JSObjectRef dateConstructor = JSValueToObject(context,
                                                  dateRef,
                                                  NULL);
    JSStringRelease(dateString);
    
    unsigned long long seconds = ((long long) time.tv_sec) * ((long long) 1000) +
        (((long long) time.tv_nsec * 10e-6l));
    
    JSValueRef arguments[] = {
        JSValueMakeNumber(context, seconds)
    };
    
    JSValueRef date = JSObjectCallAsConstructor(context, 
                                                dateConstructor, 
                                                1,
                                                arguments,
                                                NULL);
    return date;
}

JSValueRef JSValueMakeArray(JSContextRef context)
{
    JSObjectRef globalObject = JSContextGetGlobalObject(context);
    
    JSStringRef arrayString = JSStringCreateWithUTF8CString("Array");
    JSValueRef arrayRef = JSObjectGetProperty(context,
                                              globalObject,
                                              arrayString,
                                              NULL);
    JSStringRelease(arrayString);
    JSObjectRef arrayConstructor = JSValueToObject(context,
                                                   arrayRef,
                                                   NULL);
    
    JSValueRef array = JSObjectCallAsConstructor(context,
                                                 arrayConstructor,
                                                 0,
                                                 NULL,
                                                 NULL);
    
    return array;
}

struct timeval JSValueToTimeval(JSContextRef context, JSValueRef date, JSValueRef* exception)
{
    struct timeval returnValue;
    
    JSObjectRef dateRef = JSValueToObject(context, date, NULL);
    JSStringRef millisecondsString = JSStringCreateWithUTF8CString("milliseconds");
    JSValueRef milliseconds = JSObjectGetProperty(context,
                                                  dateRef,
                                                  millisecondsString,
                                                  NULL);
    JSStringRelease(millisecondsString);
    
    if (JSValueIsUndefined(context, milliseconds))
    {
        *exception = JSValueMakeNumber(context, 1);
        returnValue.tv_sec = 0;
        returnValue.tv_usec = 0;
    }
    else
    {
        unsigned long long millis = JSValueToNumber(context, milliseconds, NULL);
        returnValue.tv_sec = millis / 1000;
        returnValue.tv_usec = millis % 1000;
    }
    
    return returnValue;
}

void JSObjectAddClassMethod(JSContextRef context, JSObjectRef object, const char* methodName, JSObjectCallAsFunctionCallback method, JSPropertyAttributes attributes)
{
    JSStringRef methodString = JSStringCreateWithUTF8CString(methodName);
    JSObjectSetProperty(context,
                        object,
                        methodString,
                        JSObjectMakeFunctionWithCallback(context, methodString, method), 
                        attributes,
                        NULL);
    JSStringRelease(methodString);
}